<?php
/*
 * 简易的发券并通知功能[本功能仅处理发券以及相关的通知]
 * Added By ld 20110830
 */
//初始化加密类
import('coupon_algorithm.lib');


class SendCouponSimple extends ECBaseApp
{
    var $coupon_id; //优惠券ID
    var $mobile_code; //手机号
    var $lottery_level; //奖项等级
    var $user; //用户ID
    var $template_info_list; //模板信息
    var $login_verify; //是否需要登录(true:是;false:否;)
    var $user_id; //用户ID
    var $coupon_sn; //发放的coupon_sn

    var $coupon_sn_info; //发放的coupon_sn详细信息

    var $coupon_mod; //优惠券 model实例
    var $couponsn_mod; //优惠券号 model实例
    var $user_mod; //用户 model实例
    var $coupon_algorithm_mod; //优惠券号生成算法 model 实例

    /**
     * 构造方法[针对PHP5]
     *
     */
    public function __construct($coupon_info, $template_info_list = array())
    {
        $this->coupon_id = empty($coupon_info['coupon_id']) ? "" : $coupon_info['coupon_id'];
        $this->user = empty($coupon_info['user']) ? "" : $coupon_info['user'];
        $this->login_verify = empty($coupon_info['login_verify']) ? true : $coupon_info['login_verify'];
        $this->user_id = empty($coupon_info['user_id']) ? '' : $coupon_info['user_id'];
        $this->mobile_code = empty($coupon_info['mobile_code']) ? "" : $coupon_info['mobile_code'];
        $this->lottery_level = empty($coupon_info['lottery_level']) ? "" : $coupon_info['lottery_level'];
        $this->template_info_list = $template_info_list;

        $this->coupon_mod = & m('coupon');
        $this->couponsn_mod = & m('couponsn');
        $this->user_mod =& m('member');

        $this->coupon_algorithm_mod = new Coupon_algorithm();

        foreach ($this->template_info_list as $key => $template_info) {
            //若没有相应参数，不适合发送的，则标记为不发送
            if (empty($template_info['template'])) {
                $this->template_info_list[$key]['send'] = false;
            } //若是手机短信配置项，且没有配置手机号，则标记为不发送
            else {
                if ($key == "mobile_message_template"
                    && (empty($this->mobile_code)
                        || empty($this->lottery_level))
                ) {
                    $this->template_info_list[$key]['send'] = false;
                }
            }
        }
    }

    /**
     * 构造方法
     *
     */
    function SendCouponSimple($coupon_info, $template_info_list = array())
    {
        $this->__construct($coupon_info, $template_info_list);
    }

    /**
     * 发放优惠券类
     *
     */
    function send_coupon()
    {
        $user_id = '';

        if ($this->login_verify && !empty($this->user)) { //如果需要登录验证且能取到用户信息
            $check_rst = $this->check_coupon($this->coupon_id, $this->user);
            if ($check_rst !== true) {
                return $check_rst;
            }
            //取得当前用户是否领取过制定优惠券
            $user_id = $this->user->get("user_id");

            //构建数据模型对象
            $owen_count = $this->coupon_mod->formulate($user_id, $this->coupon_id);
            //若是买家，但已经领取过，不再重复发放，引导到"我的优惠券"画面
            if ($this->coupon_user_max_num > 0 && $owen_count >= $this->coupon_user_max_num) {
                //return  '3';//优惠券已经领完但会对已经领取过的做优先提示
            } //若是买家，尚未领取过，则发放，并引导到"我的优惠券"画面
            else {
                //验证coupon_id有效性（过滤掉不存在的coupon_id和已经过期的）
                $final_coupon_ids = $this->filter_invalid_coupon_id($this->coupon_id);

                if (!empty($final_coupon_ids)) {
                    $this->_send_coupon_by_user_id($final_coupon_ids[0], $user_id);
                    $rs = true;
                } else { //优惠券已过期
                    $rs = '3';
                }

                return $rs; //刚刚领取优惠券成功
            }
        } else {
            $user_id = $this->user_id;

            //验证coupon_id有效性（过滤掉不存在的coupon_id和已经过期的）
            $final_coupon_ids = $this->filter_invalid_coupon_id($this->coupon_id);

            if (!empty($final_coupon_ids)) {
                $this->_send_coupon_by_user_id($final_coupon_ids, $user_id);
                $rs = true;
            } else { //优惠券不存在
                $rs = '3';
            }
            return $rs; //刚刚领取优惠券成功

        }
    }

    /**
     * 验证优惠券发放条件
     *
     */
    public function check_coupon($coupon_id, $visitor)
    {
        $this->user = empty($visitor) ? "" : $visitor;
        //不允许游客操作[避免非法访问]
        if (!$this->user->has_login) {
            return '0';
        }

        //若是商家，则不发放
        if ($this->user->get("has_store") != 0) {
            return '2';
        }

        //构建数据模型对象
        $coupon_exist = $this->coupon_mod->coupon_exist($coupon_id);
        //若优惠券不存在，则不继续
        if ($coupon_exist < 1) {
            return '1';
        }

        //基本验证通过
        return true;
    }

    //#--优惠券处理函数 Begin  -------------------------------------------------------------------------
    /**
     * 向指定用户发放特定优惠券[依据用户ID]
     *
     */
    protected function _send_coupon_by_user_id($coupon_id, $user_id_list = array())
    {
        //若没有优惠券，或没有发放对象，则不继续
        if (empty($coupon_id) || empty($user_id_list)) {
            return false;
        }

        //若传入了单个用户，则组装成数组
        if (!is_array($user_id_list)) {
            $user_id_list = array(
                $user_id_list,
            );
        }

        //构建数据模型对象
        $store_mod = & m('store');
        //获得用户列表中的商家用户
        $sql = "
            SELECT store_id 
            FROM " . DB_PREFIX . "store
            WHERE " . db_create_in($user_id_list, 'store_id') . "
        ";
        $seller_id_list = $store_mod->getAll($sql);
        //滤除用户列表中的商家用户
        foreach ($user_id_list as $key => $user_id) {
            foreach ($seller_id_list as $seller_id) {
                if ($user_id === $seller_id['store_id']) {
                    unset($user_id_list[$key]);
                }
            }
        }
        //若用户列表为空，则不继续
        if (empty($user_id_list)) {
            return false;
        }
        //向指定用户发放特定优惠券
        $rst = $this->_send_coupon($coupon_id, $user_id_list);
        return $rst;
    }

    protected function _send_coupon($coupon_ids, $user_id_list = array())
    {
        //若没有优惠券，或没有发放对象，则不继续
        if (empty($coupon_ids) || empty($user_id_list)) {
            return false;
        }

        //构建数据模型对象

        $coupon_info = null;
        if (is_string($coupon_ids) || (is_array($coupon_ids) && count($coupon_ids) == 1)) {
            $coupon_id = is_string($coupon_ids) ? $coupon_ids : $coupon_ids[0];
            $coupon_info = $this->coupon_mod->get_info($coupon_id);
        }


        //向用户发放优惠券
        foreach ($user_id_list as $user_id) {

            if (!empty($coupon_info)) { //单个优惠券id
                $this->_send_single_coupon_sn($coupon_id, $coupon_info, $user_id);
            } else { //多个优惠券id
                $this->_send_multiple_coupon_sn($coupon_ids, $user_id);
            }
        }

        return true;
    }

    function _send_single_coupon_sn($coupon_id, $coupon_info, $user_id)
    {
        //产生一个优惠券
        $coupon_info_list = $this->_generate_coupon($coupon_id);


        if (!empty($coupon_info_list)) {
            $current_coupon_info = current($coupon_info_list);
            $coupon_sn = $current_coupon_info['coupon_sn'];
            //与该用户绑定
            $this->_bind_coupon($coupon_sn, $user_id);

            //方便外面调用 added by jeff liu 2011-10-14
            $this->coupon_sn[$user_id] = $coupon_sn;

            $coupon_info['coupon_sn'] = $coupon_sn;
            //若存在限定店铺
            if ($coupon_info['store_id']) {
                //整理限定店铺ID为数组
                $store_id_list = explode(',', $coupon_info['store_id']);
                //取得相关的店铺详情
                $coupon_info['allow_store_info_list'] = $this->_get_info_list($store_id_list, "store");
            }
            //若存在限定商品
            if ($coupon_info['goods_ids']) {
                //整理限定商品ID为数组
                $goods_id_list = explode(',', $coupon_info['goods_ids']);
                //取得相关的商品详情
                $coupon_info['allow_goods_info_list'] = $this->_get_info_list($goods_id_list, "goods");
            }

            //若没有相应的模板信息，则不发送
            if (!empty($this->template_info_list)) {
                //向该用户发送站内信
                $this->_message_to_user($user_id, $coupon_info, $this->template_info_list['message_template']);
                //向该用户发送Email
                $this->_mail_to_user($user_id, $coupon_info, $this->template_info_list['mail_template']);
                //向该用户发送手机短信
                $this->_mobile_message_to_user(
                    $this->mobile_code,
                    $user_id,
                    $coupon_info,
                    $this->template_info_list['mobile_message_template']
                );
            }
        }

    }

    function _send_multiple_coupon_sn($coupon_ids, $user_id)
    {
        if (is_array($coupon_ids)) {
            $coupon_infos = array();
            foreach ($coupon_ids as $key => $coupon_id) {
                $coupon_info = $this->coupon_mod->get_info($coupon_id);
                //产生一个优惠券
                $coupon_info_list = $this->_generate_coupon($coupon_id);

                if (!empty($coupon_info_list)) {
                    $current_coupon_info = current($coupon_info_list);
                    $coupon_sn = $current_coupon_info['coupon_sn'];
                    //与该用户绑定
                    $this->_bind_coupon($coupon_sn, $user_id);

                    //方便外面调用 added by jeff liu 2011-10-14
                    $this->coupon_sn[$user_id][] = $coupon_sn;

                    //方便外面调用 added by jeff liu 2012-03-07
                    $this->coupon_sn_info[$user_id][] = $current_coupon_info;

                    $coupon_info['coupon_sn'] = $coupon_sn;

                    $coupon_infos[] = $coupon_info;

                    //若存在限定店铺
                    if ($coupon_info['store_id']) {
                        //整理限定店铺ID为数组
                        $store_id_list = explode(',', $coupon_info['store_id']);
                        //取得相关的店铺详情
                        $coupon_info['allow_store_info_list'] = $this->_get_info_list($store_id_list, "store");
                    }
                    //若存在限定商品
                    if ($coupon_info['goods_ids']) {
                        //整理限定商品ID为数组
                        $goods_id_list = explode(',', $coupon_info['goods_ids']);
                        //取得相关的商品详情
                        $coupon_info['allow_goods_info_list'] = $this->_get_info_list($goods_id_list, "goods");
                    }

                }

            }
            // foreach coupon_ids end

            //若没有相应的模板信息，则不发送
            if (!empty($this->template_info_list) && !empty($coupon_infos)) {
                //向该用户发送站内信
                $this->_message_to_user_multiple(
                    $user_id,
                    $coupon_infos,
                    $this->template_info_list['message_template']
                );
                //向该用户发送Email
                $this->_mail_to_user_multiple($user_id, $coupon_infos, $this->template_info_list['mail_template']);
                //向该用户发送手机短信
                $this->_mobile_message_to_user_multiple(
                    $this->mobile_code,
                    $user_id,
                    $coupon_infos,
                    $this->template_info_list['mobile_message_template']
                );
            }
        }
        // if is_array($coupon_ids) end
    }

    //_send_multiple_coupon_sn end

    /**
     * 取得相关详情
     * Modify by wuwei 2011-08-30 [限定商品过多导致模板显示异常，特做10条记录限制]
     */
    protected function _get_info_list($id_list, $table_name)
    {
        $rst = array();
        if (empty($id_list)) {
            return $rst;
        }
        $mod = & m($table_name);
        $sql = "
            SELECT * 
            FROM " . DB_PREFIX . "{$table_name}
            WHERE {$table_name}_id " . db_create_in($id_list) . "
            limit  10
        ";
        $rst = $mod->getAll($sql);
        return $rst;
    }

    /**
     * 产生一张具体的优惠券
     */
    protected function _generate_coupon($id, $num = 1)
    {

        $use_times = $this->coupon_mod->get(
            array(
                'fields' => 'use_times,coupon_card_head,coupon_card_max_index, start_time, end_time',
                'conditions' => ' coupon_id = ' . $id
            )
        );

        $add_data = array();

        $verified_coupon = $this->verify_coupon($use_times);

        if (!$verified_coupon) { //不是一个有效的优惠券
            return $add_data;
        }

        if ($num < 1) {
            $num = 1;
        }
        $times = $use_times['use_times'];

        $str = '';
        $pix = 0;
        if (file_exists(SHARE_DATA_PATH . '/data/generate.txt')) {
            $s = file_get_contents(SHARE_DATA_PATH . '/data/generate.txt');
            $pix = intval($s);
        }
        $max = $pix + $num;
        file_put_contents(SHARE_DATA_PATH . '/data/generate.txt', $max);
        $couponsn = '';
        $tmp = '';
        $cpm = '';
        $str = '';
        $time = gmtime();

        //当前发卡数
        $coupon_card_max_index = intval($use_times['coupon_card_max_index']);

        //优惠券发放者标志位 8表示商城 7表示店铺 20101112 add by zhoubin
        $sender_flag = '8';
        if ($use_times['store_id'] != 0) //如果发放者不为0则表示是商铺发放，这里为7
        {
            $sender_flag = '7';
        }
        //20101112 add by zhoubin for 校验位添加

        for ($i = $pix + 1; $i <= $max; $i++) {
            $cpm = sprintf("%08d", $i);
            $tmp = mt_rand(1000, 9999);
            $couponsn = $cpm . $tmp;

            if ($this->coupon_algorithm_mod != null) {
                $couponsn .= $sender_flag;
                $couponsn = $this->coupon_algorithm_mod->get_new_coupon_sn($couponsn);
            }

            $coupon_card_max_index += 1;
            //有卡号命名时才生成卡号
            $coupon_card_num = empty($use_times['coupon_card_head']) || trim(
                $use_times['coupon_card_head']
            ) == '' ? '' : $use_times['coupon_card_head'] . str_pad($coupon_card_max_index, 8, '0', STR_PAD_LEFT);

            $str .= "('{$couponsn}','{$coupon_card_num}', {$id}, {$times}, {$time}),";
            $add_data[] = array(
                'coupon_sn' => $couponsn,
                'coupon_id' => $id,
                'remain_times' => $times,
                'sent_time' => $time,
                'coupon_card_num' => $coupon_card_num,
            );
        }

        $string = substr($str, 0, strrpos($str, ','));
        $this->couponsn_mod->db->query(
            "INSERT INTO {$this->couponsn_mod->table} (coupon_sn,coupon_card_num, coupon_id, remain_times, sent_time) VALUES {$string}",
            'SILENT'
        );

        if (!empty($use_times['coupon_card_head']) && trim($use_times['coupon_card_head']) != '') {
            //保存最大发卡数 只有当实际生成过卡号时才保存
            $this->coupon_mod->edit($id, array('coupon_card_max_index' => $coupon_card_max_index));
        }
        return $add_data;
    }

    /**
     * 过滤掉无效的coupon_id
     * @author jeff liu 2012-03-02
     * @param unknown_type $coupon_ids
     */
    function filter_invalid_coupon_id($coupon_ids)
    {
        $final_coupon_ids = array();

        if (is_string($coupon_ids)) {
            $sql = sprintf('SELECT * FROM %s WHERE `coupon_id`=%.0f ', $this->coupon_mod->table, (float)$coupon_ids);
        } else {
            if (is_array($coupon_ids)) {
                $tmp_coupon_ids = array();
                foreach ($coupon_ids as $coupon_id) {
                    if (!empty($coupon_id)) {
                        $tmp_coupon_ids[] = $coupon_id;
                    }
                }
                $tmp_coupon_ids = array_unique($tmp_coupon_ids);
            }
            $sql = sprintf(
                'SELECT * FROM %s WHERE `coupon_id` IN(%s)',
                $this->coupon_mod->table,
                implode(',', $tmp_coupon_ids)
            );
        }

        $coupon_info_rs = $this->coupon_mod->getAll($sql);
        if (!empty($coupon_info_rs)) {
            $current_time = gmtime();
            foreach ($coupon_info_rs as $coupon_info) {
                if ($current_time < $coupon_info['end_time'] && $coupon_info['if_issue'] == 1) { //没有过期 且 已发布
                    $final_coupon_ids[] = $coupon_info['coupon_id'];
                }
            }
        }
        return $final_coupon_ids;
    }

    /**
     * 验证coupon 信息 (coupon 不存在 获得不再有效期内)
     * @author jeff liu 2012-03-02
     * @param unknown_type $coupon_info
     */
    function verify_coupon($coupon_info)
    {
        $verified = true;

        if (empty($coupon_info)) {
            $verified = false;
        } else {
            $current_time = gmtime();
            $start_time = $coupon_info['start_time'];
            $end_time = $coupon_info['end_time'];

            if ($current_time > $end_time) { //已经结束了 不能再生成优惠券
                $verified = false;
            }
        }

        return $verified;
    }

    /**
     * 将一张优惠券与用户绑定
     */
    protected function _bind_coupon($coupon_sn, $user_id)
    {
        $this->user_mod->createRelation(
            'bind_couponsn',
            $user_id,
            array(
                $coupon_sn => array(
                    'coupon_sn' => $coupon_sn,
                    'binding_time' => gmtime()
                )
            )
        );
    }

    /**
     * 向用户发送站内信 (单个用户发单个优惠券)
     */
    protected function _message_to_user($user_id, $coupon_info, $message_template = array())
    {
        //若没有关键参数，或设定了无需发送，则不发送
        if (empty($message_template)
            || $message_template['send'] === false
            || empty($message_template['template'])
        ) {
            return;
        }

        //设定正文
        //对应配置文件:\includes\passports\default\sc-utf-8\common.lang.php
        $template = $message_template['template'];

        //整理消息参数
        $msg_params = array(
            'price' => $coupon_info['coupon_value'],
            'start_time' => local_date('Y-m-d', $coupon_info['start_time']),
            'end_time' => local_date("Y-m-d", $coupon_info['end_time']),
            'coupon_sn' => $coupon_info['coupon_sn'],
            'min_amount' => $coupon_info['min_amount'],
            'lottery_level' => $this->lottery_level,
        );

        //默认不限定店铺
        $msg_params['allow_store_info'] = LANG::get('brand_show_store_allow');
        //若存在限定店铺的
        if (!empty($coupon_info['allow_store_info_list'])) {
            $tmp_str = '';
            foreach ($coupon_info['allow_store_info_list'] as $store_info) {
                //if(!empty($tmp_str)){
                $tmp_str .= '\r\n';
                //}
                $tmp_str .= '[url=' . SITE_URL . '/index.php?app=store&id=' . $store_info['store_id'] . ']' . addslashes(
                    $store_info['store_name']
                ) . '[/url]';
            }
            //设定
            $msg_params['allow_store_info'] = $tmp_str; //限定商铺
        }

        //默认不限定商品
        $msg_params['allow_goods_info'] = LANG::get('brand_show_goods_allow');
        //若存在限定商品的
        if (!empty($coupon_info['allow_goods_info_list'])) {
            $tmp_str = '';
            foreach ($coupon_info['allow_goods_info_list'] as $goods_info) {
                //if(!empty($tmp_str)){
                $tmp_str .= '\r\n';
                //}
                $tmp_str .= '[url=' . SITE_URL . '/index.php?app=goods&id=' . $goods_info['goods_id'] . ']' . addslashes(
                    $goods_info['goods_name']
                ) . '[/url]';
            }
            //设定
            $msg_params['allow_goods_info'] = $tmp_str; //限定商品
        }
        $content = get_msg(
            $template,
            $msg_params
        );

        $ms =& ms();

        $final_content = '';

        $header_content = get_msg(
            $message_template['header_template'],
            $msg_params
        );

        $footer_content = get_msg(
            $message_template['footer_template'],
            $msg_params
        );
        $final_content = $header_content . $content . $footer_content;

        $msg_id = $ms->pm->send(MSG_SYSTEM, $user_id, '', $final_content);

    }

    /**
     * 往单个用户发送多个优惠券
     * @author jeff liu 2012-02-29
     * @param int $user_id
     * @param array $coupon_info
     * @param array $message_template
     */
    protected function _message_to_user_multiple($user_id, $coupon_infos, $message_template = array())
    {
        //若没有关键参数，或设定了无需发送，则不发送
        if (empty($message_template)
            || $message_template['send'] === false
            || empty($message_template['template'])
        ) {
            return;
        }

        //设定正文
        //对应配置文件:\includes\passports\default\sc-utf-8\common.lang.php
        $template = $message_template['template'];

        //邮件发送内容
        $data_content = '';
        $final_content = '';
        if (is_array($coupon_infos)) {
            foreach ($coupon_infos as $coupon_info) {
                //整理消息参数
                $msg_params = array(
                    'price' => $coupon_info['coupon_value'],
                    'start_time' => local_date('Y-m-d', $coupon_info['start_time']),
                    'end_time' => local_date("Y-m-d", $coupon_info['end_time']),
                    'coupon_sn' => $coupon_info['coupon_sn'],
                    'min_amount' => $coupon_info['min_amount'],
                    'lottery_level' => $this->lottery_level,
                );

                //默认不限定店铺
                $msg_params['allow_store_info'] = LANG::get('brand_show_store_allow');
                //若存在限定店铺的
                if (!empty($coupon_info['allow_store_info_list'])) {
                    $tmp_str = '';
                    foreach ($coupon_info['allow_store_info_list'] as $store_info) {
                        //if(!empty($tmp_str)){
                        $tmp_str .= '\r\n';
                        //}
                        $tmp_str .= '[url=' . SITE_URL . '/index.php?app=store&id=' . $store_info['store_id'] . ']' . addslashes(
                            $store_info['store_name']
                        ) . '[/url]';
                    }
                    //设定
                    $msg_params['allow_store_info'] = $tmp_str; //限定商铺
                }

                //默认不限定商品
                $msg_params['allow_goods_info'] = LANG::get('brand_show_goods_allow');
                //若存在限定商品的
                if (!empty($coupon_info['allow_goods_info_list'])) {
                    $tmp_str = '';
                    foreach ($coupon_info['allow_goods_info_list'] as $goods_info) {
                        //if(!empty($tmp_str)){
                        $tmp_str .= '\r\n';
                        //}
                        $tmp_str .= '[url=' . SITE_URL . '/index.php?app=goods&id=' . $goods_info['goods_id'] . ']' . addslashes(
                            $goods_info['goods_name']
                        ) . '[/url]';
                    }
                    //设定
                    $msg_params['allow_goods_info'] = $tmp_str; //限定商品
                }
                $data_content .= '<br />' . get_msg(
                    $template,
                    $msg_params
                );
            }
        }

        $ms =& ms();

        $header_content = '<br />' . get_msg(
            $message_template['header_template'],
            $msg_params
        );
        $footer_content = '<br />' . get_msg(
            $message_template['footer_template'],
            $msg_params
        );
        $final_content = $header_content . $data_content . $footer_content;

        $msg_id = $ms->pm->send(MSG_SYSTEM, $user_id, '', $final_content);

    }

    /**
     * 向该用户发送Email
     *
     */
    protected function _mail_to_user_multiple($user_id, $coupon_infos, $mail_template)
    {
        //若没有关键参数，或设定了无需发送，则不发送
        if (empty($mail_template)
            || $mail_template['send'] === false
            || empty($mail_template['template'])
        ) {
            return;
        }

        //设定正文
        //对应配置文件:\includes\arrayfiles\mailtemplate\{$template}.php
        $template = $mail_template['template'];

        $user_mod = & m('member');

        $mail = '';
        $user_info = $user_mod->get_info($user_id);

        if (is_array($coupon_infos)) {
            foreach ($coupon_infos as $coupon_info) {
//        		$user_info['coupon'] =array(
//		            'coupon_sn' => $coupon_info['coupon_sn'],
//		        );

                //默认不限定店铺
                $coupon_info['allow_store_info'] = LANG::get('brand_show_store_allow');
                //若存在限定店铺的
                if (!empty($coupon_info['allow_store_info_list'])) {
                    $tmp_str = '';
                    foreach ($coupon_info['allow_store_info_list'] as $store_info) {
                        //if(!empty($tmp_str)){
                        $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                        //}
                        $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=store&id=' . $store_info['store_id'] . '">' . addslashes(
                            $store_info['store_name']
                        ) . '</a>';
                    }
                    //设定
                    $coupon_info['allow_store_info'] = $tmp_str; //限定商铺
                }

                //默认不限定商品
                $coupon_info['allow_goods_info'] = LANG::get('brand_show_goods_allow');
                //若存在限定商品的
                if (!empty($coupon_info['allow_goods_info_list'])) {
                    $tmp_str = '';
                    foreach ($coupon_info['allow_goods_info_list'] as $goods_info) {
                        //if(!empty($tmp_str)){
                        $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                        //}
                        $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=goods&id=' . $goods_info['goods_id'] . '">' . addslashes(
                            $goods_info['goods_name']
                        ) . '</a>';
                    }
                    //设定
                    $coupon_info['allow_goods_info'] = $tmp_str; //限定商品
                }

                $mail .= '<br />' . get_mail(
                    $template,
                    array(
                        'user' => $user_info,
                        'coupon' => $coupon_info,
                    )
                );
            }
        }

        $this->_mailto($user_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
    }


    protected function _mail_to_user($user_id, $coupon_info, $mail_template)
    {
        //若没有关键参数，或设定了无需发送，则不发送
        if (empty($mail_template)
            || $mail_template['send'] === false
            || empty($mail_template['template'])
        ) {
            return;
        }

        //设定正文
        //对应配置文件:\includes\arrayfiles\mailtemplate\{$template}.php
        $template = $mail_template['template'];

        $user_mod = & m('member');
        $user_info = $user_mod->get_info($user_id);
        $user_info['coupon'] = array(
            'coupon_sn' => $coupon_info['coupon_sn'],
        );

        //默认不限定店铺
        $coupon_info['allow_store_info'] = LANG::get('brand_show_store_allow');
        //若存在限定店铺的
        if (!empty($coupon_info['allow_store_info_list'])) {
            $tmp_str = '';
            foreach ($coupon_info['allow_store_info_list'] as $store_info) {
                //if(!empty($tmp_str)){
                $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                //}
                $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=store&id=' . $store_info['store_id'] . '">' . addslashes(
                    $store_info['store_name']
                ) . '</a>';
            }
            //设定
            $coupon_info['allow_store_info'] = $tmp_str; //限定商铺
        }

        //默认不限定商品
        $coupon_info['allow_goods_info'] = LANG::get('brand_show_goods_allow');
        //若存在限定商品的
        if (!empty($coupon_info['allow_goods_info_list'])) {
            $tmp_str = '';
            foreach ($coupon_info['allow_goods_info_list'] as $goods_info) {
                //if(!empty($tmp_str)){
                $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                //}
                $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=goods&id=' . $goods_info['goods_id'] . '">' . addslashes(
                    $goods_info['goods_name']
                ) . '</a>';
            }
            //设定
            $coupon_info['allow_goods_info'] = $tmp_str; //限定商品
        }

        $mail = get_mail(
            $template,
            array(
                'user' => $user_info,
                'coupon' => $coupon_info,
            )
        );

        $this->_mailto($user_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
    }

    /**
     * 向该用户发送手机短信
     * Added By ld 20110826
     */
    protected function _mobile_message_to_user($mobile_code, $user_id, $coupon_info, $mobile_message_template)
    {
        //若没有设定必要参数或设定为不需要发送的
        if (empty($mobile_code)
            || empty($user_id)
            || !isset($mobile_message_template)
            || $mobile_message_template['send'] === false
        ) {
            //则不发送
            return false;
        }

        //设定正文
        //对应配置文件:\includes\arrayfiles\mobilePMtemplate\{$template}.php
        $template = $mobile_message_template['template'];

        //取得用户信息
        $user_mod = & m('member');
        $user_info = $user_mod->get_info($user_id);
        //完善用户信息
        $user_info['coupon'] = array(
            'coupon_sn' => $coupon_info['coupon_sn'],
        );

        $coupon_info['lottery_level'] = $this->lottery_level;

        //默认不限定店铺
        $coupon_info['allow_store_info'] = LANG::get('brand_show_store_allow');
        //若存在限定店铺的
        if (!empty($coupon_info['allow_store_info_list'])) {
            $tmp_str = '';
            foreach ($coupon_info['allow_store_info_list'] as $store_info) {
                //if(!empty($tmp_str)){
                $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                //}
                $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=store&id=' . $store_info['store_id'] . '">' . addslashes(
                    $store_info['store_name']
                ) . '</a>';
            }
            //设定
            $coupon_info['allow_store_info'] = $tmp_str; //限定商铺
        }

        //默认不限定商品
        $coupon_info['allow_goods_info'] = LANG::get('brand_show_goods_allow');
        //若存在限定商品的
        if (!empty($coupon_info['allow_goods_info_list'])) {
            $tmp_str = '';
            foreach ($coupon_info['allow_goods_info_list'] as $goods_info) {
                //if(!empty($tmp_str)){
                $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                //}
                $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=goods&id=' . $goods_info['goods_id'] . '">' . addslashes(
                    $goods_info['goods_name']
                ) . '</a>';
            }
            //设定
            $coupon_info['allow_goods_info'] = $tmp_str; //限定商品
        }

        //手机短信相关参数
        $params = array(
            'user' => $user_info,
            'coupon' => $coupon_info,
        );
        //取得手机短信内容
        $content = get_mobilePM(
            $template,
            $params
        );
        if (!empty($content)) {
            return $this->send_mobile_pm($mobile_code, $content['message']);
        }
        return true;
    }

    protected function _mobile_message_to_user_multiple($mobile_code, $user_id, $coupon_infos, $mobile_message_template)
    {
        //若没有设定必要参数或设定为不需要发送的
        if (empty($mobile_code)
            || empty($user_id)
            || !isset($mobile_message_template)
            || $mobile_message_template['send'] === false
        ) {
            //则不发送
            return false;
        }

        //设定正文
        //对应配置文件:\includes\arrayfiles\mobilePMtemplate\{$template}.php
        $template = $mobile_message_template['template'];

        //取得用户信息
        $user_mod = & m('member');
        $user_info = $user_mod->get_info($user_id);

        $final_content = '';

        if (is_array($coupon_infos)) {
            foreach ($coupon_infos as $coupon_info) {
                //完善用户信息
                $user_info['coupon'] = array(
                    'coupon_sn' => $coupon_info['coupon_sn'],
                );

                $coupon_info['lottery_level'] = $this->lottery_level;

                //默认不限定店铺
                $coupon_info['allow_store_info'] = LANG::get('brand_show_store_allow');
                //若存在限定店铺的
                if (!empty($coupon_info['allow_store_info_list'])) {
                    $tmp_str = '';
                    foreach ($coupon_info['allow_store_info_list'] as $store_info) {
                        //if(!empty($tmp_str)){
                        $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                        //}
                        $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=store&id=' . $store_info['store_id'] . '">' . addslashes(
                            $store_info['store_name']
                        ) . '</a>';
                    }
                    //设定
                    $coupon_info['allow_store_info'] = $tmp_str; //限定商铺
                }

                //默认不限定商品
                $coupon_info['allow_goods_info'] = LANG::get('brand_show_goods_allow');
                //若存在限定商品的
                if (!empty($coupon_info['allow_goods_info_list'])) {
                    $tmp_str = '';
                    foreach ($coupon_info['allow_goods_info_list'] as $goods_info) {
                        //if(!empty($tmp_str)){
                        $tmp_str .= '<br />&nbsp;&nbsp;&nbsp; ';
                        //}
                        $tmp_str .= '<a href="' . SITE_URL . '/index.php?app=goods&id=' . $goods_info['goods_id'] . '">' . addslashes(
                            $goods_info['goods_name']
                        ) . '</a>';
                    }
                    //设定
                    $coupon_info['allow_goods_info'] = $tmp_str; //限定商品
                }

                //手机短信相关参数
                $params = array(
                    'user' => $user_info,
                    'coupon' => $coupon_info,
                );
                //取得手机短信内容
                $content = get_mobilePM(
                    $template,
                    $params
                );
                $final_content .= $content['message'];
            }
        }

        if (!empty($final_content)) {
            return $this->send_mobile_pm($mobile_code, $final_content);
        }
        return true;
    }

    /**
     * 获得已发送的coupon_sn
     * @author jeff liu 2012-03-01
     */
    function get_sent_coupon_sn()
    {
        return $this->coupon_sn;
    }

    /**
     * 获得已发送的coupon_sn 详细信息
     * @author jeff liu 2012-03-07
     */
    function get_sent_coupon_sn_info()
    {
        return $this->coupon_sn_info;
    }
}

?>